import axios from "axios";
import { ElMessage } from "element-plus";
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from "@/stores/usersStore";
import router from "@/router";
//通用路径
const httpInstance = axios.create({
    baseURL: "/api",
    timeout: 5000
})
//拦截器
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    const userStore = useUserStore()
    // 2. 按照后端的要求拼接token数据
    const token = userStore.userInfo?.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => Promise.reject(error))

// axios响应式拦截器
httpInstance.interceptors.response.use(
    res => {
        if (res.data.code == 0) {
            ElMessage({ type: 'error', message: res.data.msg ? res.data.msg : '出错了，请稍后再试！' })
            throw new Error(res.data.msg ? res.data.msg : '未知错误')
        }
        return res.data
    },
    error => {
        const userStore = useUserStore()

        //处理token失效情况
        if (error.response?.status === 401) {
            userStore.removeUserInfo()
            ElMessage({ type: 'warning', message: "请登录！" })
            router.push('/login')
        } else {
            if (error.response == null) {
                ElMessage({ type: 'error', message: error.message })
            } else {

                ElMessage({ type: 'error', message: error.response?.statusText + ":" + error.response?.status })
            }
        }
        return Promise.reject(error)
    })

export default httpInstance